"use strict";

const axios = require("axios");
const urljoin = require("url-join");
const semver = require("semver");

//获取npm接口数据
function getNpmInfo(npmName, registry) {
  if (!npmName) {
    return null;
  }
  registry = registry || getDefaultRegistry();
  const npmInfoUrl = urljoin(registry, npmName);
  return axios
    .get(npmInfoUrl)
    .then((res) => {
      if (res.status === 200) {
        return res.data;
      } else {
        return null;
      }
    })
    .catch((err) => Promise.reject(err));
}

function getDefaultRegistry(isOrigin = false) {
  return isOrigin
    ? "https://registry.npmjs.org"
    : "https://registry.npm.taobao.org";
}

async function getNpmVersions(npmName, resigtry) {
  const data = await getNpmInfo(npmName, resigtry);
  if (data) {
    return Object.keys(data.versions);
  }
  return null;
}

function getSemverVersions(baseVersion, npmVersions) {
  npmVersions = npmVersions
    .filter((item) => semver.satisfies(item, `^${baseVersion}`)) //版本号过滤
    .sort((a, b) => semver.gt(b, a)); //版本号排序
  return npmVersions;
}

async function getNpmSemverVersions(baseVersion, npmName, resigtry) {
  const versions = await getNpmVersions(npmName, resigtry);
  const newVersions = getSemverVersions(baseVersion, versions);
  if (newVersions && newVersions.length > 0) {
    return newVersions[0];
  }
}

async function getNpmLatestVersion(npmName, registry) {
  let versions = await getNpmVersions(npmName, registry);
  if (versions) {
    versions = versions.sort((a, b) => semver.gt(b, a));
    return versions[0];
  }
  return null;
}

module.exports = {
  getNpmInfo,
  getNpmVersions,
  getNpmSemverVersions,
  getDefaultRegistry,
  getNpmLatestVersion,
};
